const DB_NAME = "oceanchat-db"; // 数据库名称
const DB_VERSION = 4;
const STORE_NAME = "messages"; // 表名

let db: IDBDatabase | null = null;
let openPromise: Promise<IDBDatabase> | null = null;

export function openDB(): Promise<IDBDatabase> {
  if (db) return Promise.resolve(db);
  if (openPromise) return openPromise;

  openPromise = new Promise((resolve, reject) => {
    const request = indexedDB.open(DB_NAME, DB_VERSION);

    request.onerror = () => {
      openPromise = null;
      reject(request.error);
    };

    request.onsuccess = () => {
      db = request.result;

      // 监听数据库版本变更事件，关闭老连接
      db.onversionchange = () => {
        console.warn("数据库版本发生变更，正在关闭旧连接");
        db?.close();
        db = null;
        openPromise = null;
      };

      resolve(db);
    };

    request.onupgradeneeded = () => {
      const db = request.result;
      if (!db.objectStoreNames.contains(STORE_NAME)) {
        const store = db.createObjectStore(STORE_NAME, {
          keyPath: "id",
          autoIncrement: true,
        });
        store.createIndex("senderId", "senderId", { unique: false });
        store.createIndex("receiverId", "receiverId", { unique: false });
        //store.createIndex("groupId", "groupId", { unique: false });
        store.createIndex("id", "id", { unique: false });
        store.createIndex("type", "type", { unique: false });
        store.createIndex("timestamp", "timestamp", { unique: false });
      }
    };
  });

  return openPromise;
}

// utils/indexedDb.ts
import type { ChatMessage } from "@/stores/app";

export async function addMessage(message: ChatMessage): Promise<void> {
  const db = await openDB();
  return new Promise((resolve, reject) => {
    const tx = db.transaction(STORE_NAME, "readwrite");
    tx.onerror = () => reject(tx.error);
    tx.onabort = () => reject(new Error("事务被中止"));

    const store = tx.objectStore(STORE_NAME);
    const request = store.put(message);
    request.onsuccess = () => resolve();
    request.onerror = () => reject(request.error);
  });
}

export async function getMessagesByChat(
  type: "PRIVATE" | "GROUP",
  id: number,
): Promise<ChatMessage[]> {
  const db = await openDB();
  console.log("params", type, id);
  return new Promise((resolve, reject) => {
    const tx = db.transaction(STORE_NAME, "readonly");
    const store = tx.objectStore(STORE_NAME);

    const messages: ChatMessage[] = [];
    const request = store.openCursor();
    const user_id = Number(localStorage.getItem('user_id'));

    request.onerror = () => reject(request.error);

    request.onsuccess = (event) => {
      console.log("游标开启成功");
      const cursor = (event.target as IDBRequest).result;
      if (cursor) {
        const record: ChatMessage = cursor.value;

        // 你这里根据自己的设计来判定消息是否属于当前会话
        // 例如统一用id作为会话id字段，且type匹配
        const chatId = record.senderId;

        if (record.type === type && (chatId === id || chatId === user_id)) {
          console.log("get chat", chatId);
          messages.push(record);
        }

        cursor.continue();
      } else {
        // 遍历结束
        resolve(messages);
      }
    };
  });
}
